<? // " vim:set fdm=indent ts=2 ai et sts=2 sw=2 tw=0:
function weather_get_list($html)
{
  preg_match_all ("|<!--(.*)--><(.*)>|U", $html, $matches, PREG_PATTERN_ORDER);
  $names = $matches[1]; unset($matches);
  preg_match_all ("|<option value=\"(.*)\">|U", $html, $pages, PREG_PATTERN_ORDER);
  $page_list = $pages[1]; unset($pages);
  $values = Array("real_data_46692.htm");
  for ($i = 0; $i < count($page_list); $i++)
    array_push($values, $page_list[$i]);
  unset($page_list);
  $list = @array_combine ($names, $values);
  return $list;
}

function text_get_section($text, $begin, $end)
{
  $blen = strlen($begin);
  $c = strstr($text, $begin);
  $dlen = strlen(strstr($c, $end));
  $clen = strlen($c);
  $elen = strlen($end);
  $e = substr($c, $blen, $clen - $blen - $dlen - $elen);
  return $e;
}

function weather_html_get_data($html)
{
  $name = Array( "觀測時間", "天氣現象", "溫度(℃)", "風向", "風力(級)", "陣風(級)", "能見度(公里)", "相對溼度(%)", "海平面氣壓(百帕)", "累積雨量(毫米)", "紫外線指數");
  $begin = "<table border=0 width=250 summary=\"排版用表格\">";
  $end   = "</table>";
  $table_text = text_get_section($html, $begin, $end);
  preg_match_all ("|<td[^>]*>(.*)</td>|U", $table_text, $matches, PREG_PATTERN_ORDER);
  $data = str_replace("&nbsp;", " ", $matches[1]);
  $data = str_replace("&nbsp", " ", $data);
  $data[1] = text_get_section($data[1], "title=\"", "\"");
  $data = array_combine($name, $data);
  return $data;
}

function GetWeather($areaname)
{
  define (PREFIX, "http://www.cwb.gov.tw/V5/observe/real/");
  $http = new cURL();
  $result = $http->get(PREFIX."real_data_46692.htm");
  $result = iconv("big5","utf8",$result);
  $list = weather_get_list($result);
  $data = weather_html_get_data($result);

  if ($areaname != "台北")
  {
    if ($areaname)
    {
      if ($list[$areaname])
      {
        $result = $http->get(PREFIX.$list[$areaname]);
        $result = iconv("big5","utf8",$result);
        $list = weather_get_list($result);
        $data = weather_html_get_data($result);
      } else
      {
        echo "目前可提供的氣象資料為:";
        foreach ($list as $key => $value)
        {
          echo $key." ";
        }
        echo " \n";
        die("以上查無資料");
      }
    } 
  } 
  $ans = "";
  foreach ($data as $key => $value)
    $ans .= $key.":".$value."\n";
  return $ans;
}
?>
